import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { Input, Button } from 'antd';

const CustomPrompt = ({ message, onConfirm, onCancel }) => {
  const [inputValue, setInputValue] = useState('');

  const handleConfirm = () => {
    onConfirm(inputValue);
  };

  const handleCancel = () => {
    onCancel('User canceled the input.');
  };

  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        background: 'rgba(0, 0, 0, 0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000,
      }}
    >
      <div
        style={{
          background: 'white',
          padding: '20px',
          borderRadius: '5px',
          boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
          maxWidth: '400px',
          width: '100%',
        }}
      >
        <p style={{ marginBottom: '15px', fontSize: '16px', color: '#333' }}>{message}</p>
        <Input.TextArea
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="请输入内容"
          style={{ width: '100%', marginBottom: '15px' }}
          autoFocus
          rows={5}  // 控制显示的行数
        />
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
          <Button onClick={handleConfirm} type="primary">
            确认
          </Button>
          <Button onClick={handleCancel} type="default">
            取消
          </Button>
        </div>
      </div>
    </div>
  );
};

export const customPrompt = (message) => {
  return new Promise((resolve, reject) => {
    const container = document.createElement('div');
    document.body.appendChild(container);
    const root = createRoot(container);

    const handleConfirm = (inputValue) => {
      resolve(inputValue);
      root.unmount();
      document.body.removeChild(container);
    };

    const handleCancel = (reason) => {
      reject(new Error(reason));  // Create an Error object to pass the reason
      root.unmount();
      document.body.removeChild(container);
    };

    root.render(
      <CustomPrompt message={message} onConfirm={handleConfirm} onCancel={handleCancel} />
    );
  });
};
